package com.syg.servlet01;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 设置content-disposition响应头，让浏览器下载文件
 */
@WebServlet("/disposition")
public class _05_Browser_content_disposition extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //清空输出流
        OutputStream respOut = null;
        try{
            resp.reset();
            //设置浏览器响应头
            resp.setHeader("content-disposition", "attachment;filename=abc.png");
            resp.setContentType("application/octet-stream");
            //获取文件流(1,获取上下文对象,2,获取资源流对象)
            InputStream picOut = this.getServletContext().getResourceAsStream("/Images/BrowserRead.png");
            //定义缓冲区:提高下载速度
            byte[] buffer = new byte[1024];
            int len = 0;
            //获取响应输出流对象
            respOut = resp.getOutputStream();
            while ((len = picOut.read(buffer))>0){
                //使用响应流对象输出缓冲区中的文件流
                respOut.write(buffer);
            }
            respOut.flush();
        } finally {
            if(null != respOut){
                respOut.close();
            }
        }
    }
}
